# -*- coding: iso-8859-1 -*-
#sEngine PackageManager developped by Julien Nunca

#Plus opérand, à reprendre plus tard.

import os.path
import glob
import hashlib
import time
import sys
import zipfile

def listDirectory(path):
  #Recursivly list directories in path
  dirs = []
  l = glob.glob(path+'/*')
  for i in l:
    if os.path.isdir(i): dirs.append(i)
  return dirs

def listFiles(path):
  files = []
  l = glob.glob(path+'/*')
  for i in l:
    if not os.path.isdir(i): files.append(i)
  return files

def stripName(name):
  return name.replace('/', '.')


def mkLine(path):
  strings = []
  dirs = listDirectory(path)
  filesInDir = listFiles(path)

  for f in filesInDir:
    file = open(f, 'r')
    st = file.read()
    strings.append([os.path.splitext(f)[0], os.path.splitext(f)[1][1:], str(hashlib.sha224(st).hexdigest())])
    file.close()
  for d in dirs:
    strings.extend(mkLine(d))
  return strings

def checkTwins(l):
  for item in l:
    if l.count(item) > 1:
      return True
  return False


if __name__ == '__main__':

  if len(sys.argv) < 3:
    print 'Usage: python ' + sys.argv[0] + ' path_to_dir package_name'
  else:
    path = sys.argv[1]
    target = sys.argv[2]

    zfile = zipfile.ZipFile(target, 'w')

    f = open('index.rl', 'w')
    lines = mkLine(path)

    #Display a warning if twins are spotted
    if checkTwins([x[2] for x in lines]):
      warning =  "##############################################\n"
      warning += "#     WARNING: Twin resource detected!      #\n"
      warning += "##############################################"
      f.write(warning + '\n')
      print warning

    f.write('#Generated ' + time.ctime() + '\n')
    f.write('#General format: id | ext | sha\n')
    for l in lines:
      zfile.write(l[0]+'.'+l[1])
      for i, c in enumerate(l):
        f.write(c.replace('/', '.'))
        if i != 3:
          f.write('\t')
      f.write('\n')
    f.close()

    zfile.write('index.rl')
    zfile.close()

    os.remove('index.rl')

